package com.example.myproject.controller;

import com.example.myproject.dao.PersonRepository;
import com.example.myproject.entity.Person;
import com.example.myproject.service.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class PersonController {
    @Autowired
    PersonRepository personRepository;
    @Autowired
    private PersonService personService;

    /**
     *查询所有人员
     *
     * @return
     */
    @GetMapping(value = "/person")
    private List<Person> personList(){
        return personRepository.findAll();
    }


    /**
     * 通过年龄来查询
     * @param age
     * @return
     */
    @GetMapping(value="/person/age/{age}")
    public List<Person> personListByAge(@PathVariable("age") Integer age){
        return personRepository.findByAge(age);
    }

    /***
     * 增加
     * @param name
     * @param age
     * @return
     * */
    @PostMapping(value="/person")
    public Person personAdd(@RequestParam("name") String name,@RequestParam("age") Integer age){
        Person person=new Person();
        person.setName(name);
        person.setAge(age);

        return personRepository.save(person);
    }

    /**
     * 查找
     *
     * @param  id
     * @return
     */
    @GetMapping(value="/person/{id}")
    public Person personFindOne(@PathVariable("id") Integer id){
        return personRepository.findOne(id);
    }

    /**
     * 删除
     *
     * @param id
     * */
    @DeleteMapping(value="/person/{id}")
    public void personDelete(@PathVariable("id") Integer id){
        personRepository.delete(id);
    }

    /**
     * 更新
     *
     * @param id
     * @param name
     * @param age
     * @return
     */

    @PutMapping(value = "/person/{id}")
    public Person personUpdate(@PathVariable("id") Integer id,@RequestParam("name") String name,@RequestParam("age") Integer age){
        Person person=new Person();
        person.setId(id);
        person.setName(name);
        person.setAge(age);
        return personRepository.save(person);
    }

    /**
     *事务测试
     */
    @PostMapping("/person/two")
    public void personTwo(){
        personService.insertTwo();
    }
}
